package br.inf.solutions.apresentacoes.ssp.control;

import java.util.HashMap;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import br.com.vexillum.model.IActivatedEntity;
import br.com.vexillum.util.Return;
import br.inf.solutions.apresentacoes.ssp.control.validator.AddressValidator;
import br.inf.solutions.apresentacoes.ssp.model.Provider;

@Service
@Scope("prototype")
public class ProviderController extends BaseController<Provider>{

	public ProviderController() {
		super(Provider.class);
	}
	
	@Override
	public Return save() {
		if(!checkAddress().isValid()){
			getEntity().setAddress(null);
		}
		return super.save();
	}
	
	private Return checkAddress(){
		HashMap<String, Object> data = new HashMap<>();
		data.put("entity", getEntity().getAddress());
		data.put("action", "saveProvider");
		
		AddressValidator validator = new AddressValidator(data);
		
		return validator.validate();
	}
	
	@Override
	public Return listAll() {
		String sql = "FROM " + classEntity.getSimpleName() + " WHERE active = true ORDER BY fantasyName";
		if(data.get("entity") == null || (((IActivatedEntity) data.get("entity")).getActive() == null) || !((IActivatedEntity) data.get("entity")).getActive()){
			sql = sql.replace(" WHERE active = true", "");
		}
		data.put("sql", sql);
		return super.searchByHQL();
	}
}